//
//  MHNewsDetailViewController.m
//  MHO
//
//  Created by papo on 2/17/14.
//  Copyright (c) 2014 maihoang. All rights reserved.
//

#import "MHNewsDetailViewController.h"
#import "Lib.h"

@interface MHNewsDetailViewController ()
{
//    NSTimer* timerCheck;
    NSInteger   numberOfRequests;
    BOOL setHeight;
    float       scaleHeight;
}
@property (weak, nonatomic) IBOutlet UIView *navibarView;

@end

@implementation MHNewsDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    // check if need to set scalepage to fit

    [self.webView setScalesPageToFit:YES];
//    [self.webView.scrollView setScrollEnabled:NO];
    self.webView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
//    self.view.layer.borderColor = [UIColor greenColor].CGColor;
//    self.view.layer.borderWidth = 2;
    CGRect frame = self.view.frame;
    frame.size.height -= (self.navibarView.frame.size.height + self.navibarView.frame.origin.y);
    frame.origin.y = self.navibarView.frame.size.height + self.navibarView.frame.origin.y;
    self.webView.frame = frame;
    [self.view addSubview:self.webView];

    if (self.htmlString) {
        [self loadHTMLString:self.htmlString baseURL:nil];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    NSLog(@"topbar y=%f", self.navibarView.frame.origin.y);
//    NSLog(@"self html string: %@", _htmlString);
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)openUrl:(NSString *)url {
    NSString* str = [NSString stringWithFormat:@"http://mho.vn/%@", url];
    NSURLRequest* request = [NSURLRequest requestWithURL:[NSURL URLWithString:str]];
    NSLog(@"url: %@ %@", str, [NSURL URLWithString:str]);
    numberOfRequests = 0;
    setHeight = NO;
    [self.webView loadRequest:request];
}

- (void)loadHTMLString:(NSString*)string baseURL:(NSURL*)url {
    [self.webView loadHTMLString:string baseURL:url];
    numberOfRequests = 0;
    setHeight = NO;
}

#pragma mark - WebView Delegate 
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSLog(@"webView start load with request: %@", request.URL.absoluteString);
    if (request.URL.absoluteString == nil || [request.URL.absoluteString isEqualToString:@"about:blank"]) {
//        return NO;
    }
    numberOfRequests++;
    return YES;
}


- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    NSLog(@"loading failed!");
    numberOfRequests--;
    [Lib removeLoadingView];
    [self performSelector:@selector(reloadAll) withObject:nil afterDelay:.5];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    numberOfRequests--;
    if (numberOfRequests <= 0) {
        NSLog(@"load web done!");
    }
//    else return;
    [Lib removeLoadingView];
    if (self.webView.scalesPageToFit) {
        int fontSize = 300;
        NSString *jsString = [[NSString alloc] initWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%d%%'", fontSize];
        [self.webView stringByEvaluatingJavaScriptFromString:jsString];
        CGRect frame = self.webView.frame;
        frame.size.width = self.view.frame.size.width;
        self.webView.frame = frame;
    }
    [self performSelector:@selector(reloadAll) withObject:nil afterDelay:0.5];
}

- (void)webViewDidStartLoad:(UIWebView *)webView {
    [Lib showLoadingView];
}

- (void)reloadAll {
    if ([self.webView isLoading]) {
        return;
    }
    
    
    if (1 ){
        // fix font size
//        [self.webView sizeToFit];
        int w = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.width"] floatValue];
        scaleHeight = self.webView.frame.size.width / w;
        
//        NSString *jsCommand = [NSString stringWithFormat:@"document.body.style.zoom = %f;", scaleHeight];
//        [self.webView stringByEvaluatingJavaScriptFromString:jsCommand];
        
        // change font size
//        int fontSize = (int)(100 / scaleHeight / 2);
//        NSString *jsString = [[NSString alloc] initWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%d%%'", fontSize];
//        [self.webView stringByEvaluatingJavaScriptFromString:jsString];
        
        // set correct frame
//        CGRect frame = self.webView.frame;
//        frame.size.height = self.webView.scrollView.contentSize.height;
//        [self.webView setFrame:frame];
//        NSLog(@"webview height: %f", frame.size.height);

        //    [self performSelector:@selector(delayRefresh) withObject:nil afterDelay:1.5];
        [self performSelector:@selector(delayRefresh) withObject:nil afterDelay:.5];
        
        setHeight = YES;
    }
}

- (void)delayRefresh {
    [self.tableView reloadData];
}

- (IBAction)backButtonPressed:(id)sender {
//    [self dismissViewControllerAnimated:YES completion:nil];
    self.htmlString = nil;
    [Lib removeLoadingView];
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - TableView Source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }
    return 0;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString* CellInditifier = @"Cell";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:CellInditifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] init];
        if (indexPath.section == 0) {
//            [cell.contentView addSubview:self.webView];
        }
    }
    [cell setNeedsDisplay];
    [cell layoutIfNeeded];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    float height = 20;
    if (indexPath.section == 0) {
        height = self.webView.frame.size.height;
        
//        float newSize = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.offsetHeight"] floatValue];
    }
    return height;
}

#pragma mark - TableView Delegate

- (BOOL)shouldAutorotate {
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAll;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    return YES;
}
@end
